#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <openssl/evp.h>

int sm4_cbc_encrypt(const unsigned char *key, const unsigned char *iv,
                    const unsigned char *in, size_t in_len,
                    unsigned char *out, size_t *out_len) {
    EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
    if (!ctx) return -1;

    if (EVP_EncryptInit_ex(ctx, EVP_sm4_cbc(), NULL, key, iv) != 1 ||
        EVP_EncryptUpdate(ctx, out, (int*)out_len, in, in_len) != 1) {
        EVP_CIPHER_CTX_free(ctx); return -1;
    }

    int tmplen;
    EVP_EncryptFinal_ex(ctx, out + *out_len, &tmplen);
    *out_len += tmplen;
    EVP_CIPHER_CTX_free(ctx);
    return 0;
}

int main() {
    const char *msg = "fsl";
    unsigned char key[16] = {
        0x51,0x00,0xa4,0x6f,0xbb,0x9a,0x72,0x69,
        0xaa,0x83,0x17,0x3c,0x1e,0xbf,0xe5,0x5d
    };
    unsigned char iv[16] = {
        0xf8,0x8b,0x7a,0xcf,0x32,0xe2,0x5e,0xc9,
        0x61,0xe1,0x11,0xa8,0x18,0x6a,0x5d,0xd9
    };

    unsigned char ciphertext[256];
    size_t out_len = sizeof(ciphertext);

    if (sm4_cbc_encrypt(key, iv, (unsigned char*)msg, strlen(msg), ciphertext, &out_len) == 0) {
        printf("SM4 encrypt success, ciphertext length: %zu bytes\n", out_len);
        // 可选：保存密文
        FILE *fp = fopen("sm4.cipher", "wb");
        fwrite(ciphertext, 1, out_len, fp);
        fclose(fp);
    } else {
        fprintf(stderr, "SM4 encrypt failed\n");
        return 1;
    }
    return 0;
}
